import img1 from '@/assets/login/1.jpg';
import { ftUserinfo } from '@/service/modules/users';
import { setLocalStorage } from '@/utils/local';
import { Button, Form, FormProps, Input, message } from 'antd';
import md5 from 'crypto-js/md5';
import { memo } from 'react';
import { useModel, useNavigate } from 'umi';
import './index.less';

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};
const LoginPage: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const { loginAction } = useModel('usersModel');
  const navigate = useNavigate();
  const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
    console.log('Success:', values);
    const res = await loginAction({
      name: values.username,
      password: md5(values.password || '').toString(),
    });
    const { code, data, message: msg } = res;
    if (code === 200 && data) {
      message.success('登录成功');
      setLocalStorage('token', data?.token);
      const res2 = await ftUserinfo();
      if (res2.code === 200 && res2.data) {
        const { id, level, telPhone, name, avatar } = res2.data;
        setInitialState({
          id,
          level,
          telPhone,
          name,
          avatar,
        });
      }
      navigate('/');
    }
  };

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <>
      <div className="bg-login">
        <img className="img" src={img1}></img>
      </div>
      <div className="login">
        <div className="login-box animate__animated animate__bounceIn">
          <span className="lb-title">博客后台</span>
          <Form
            className="lb-form"
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 12 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item<FieldType> label="用户名" name="username" rules={[{ required: true }]}>
              <Input className="custom-input" />
            </Form.Item>

            <Form.Item<FieldType> label="密码" name="password" rules={[{ required: true }]}>
              <Input.Password className="custom-input" />
            </Form.Item>

            <Form.Item label={null}>
              <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </>
  );
};

export default memo(LoginPage);
